import struct

'''
文件进制转换
'''


def encode(s):
    tmp = []
    for c in s:
        tmp.append(bin(ord(c)).replace('0b', ''))
    str_bin = ' '.join(tmp)
    return (str_bin)


def decode(s):
    bin_str = ''.join([chr(i) for i in [int(b, 2) for b in s.split(' ')]])
    return bin_str


def fill_key(file, key):
    passwd = []
    file_len = len(file)
    while len(passwd) < file_len:
        # print (len(passwd),file_len)
        for i in key:
            passwd.append(i)
    return passwd[:file_len]


def fill_8(user_list):
    list2 = []
    for i in user_list:
        while len(i) < 8:
            i = '0' + i
        list2.append(i)
    return list2


def file_encode(path):
    f = open(path, 'rb')
    tmp = []
    for i in f.read():
        tmp.append(bin(i).replace('0b', ''))
    f.close()
    return (tmp)


def process_file(source, key):
    out = []
    for i in source:
        tmp = []
        tmp2 = []
        for b, key in zip(i, ''.join(fill_key(i, encode('hello').replace(' ', '')))):
            tmp.append(int(b) ^ int(key))
        for num in tmp:
            tmp2.append(str(num))
        st = ''.join(tmp2)
        out.append(st)
    return out



def file_decode(source, des_path):
    f = open(des_path, 'wb')
    for x in source:
        a = struct.pack('B', int(x, 2))
        f.write(a)
    f.close()
    return True

def byteen(from_path,key,outpath):
    source = file_encode(from_path)
    fill_source = fill_8(source)
    #print(fill_source)
    process_res = process_file(fill_source, key=key)
    file_decode(process_res, outpath)

def bytede(key):
    source = file_encode(r'./my_encode.zip')
    fill_source = fill_8(source)
    #print(fill_source)
    process_res = process_file(fill_source, key=key)
    file_decode(process_res, r'./my_decode.zip')

if __name__ == "__main__":
    '''
    加密
    '''
    source = file_encode(r'./output.zip')
    fill_source = fill_8(source)
    print(fill_source)
    process_res = process_file(fill_source, key='mylove')
    file_decode(process_res, r'./my_encode.zip')

    '''
    解密
    '''
    source = file_encode(r'./my_encode.zip')
    fill_source = fill_8(source)
    print(fill_source)
    process_res = process_file(fill_source, key='mylove')
    file_decode(process_res, r'./my_decode.zip')